import logging
import os
import time

from handle.handlesysconfig import conf
from handle.handle_path import LOGDIR


class HandleLog(object):
    @staticmethod
    def create_log():
        """
        创建日志，设置日志等级
        :return:
        """
        autolog = logging.getLogger(conf.get("log", "name"))
        autolog.setLevel(conf.get("log", "level"))

        """
        创建输出到控制台的日志等级
        并添加到日志搜集器
        """
        ssh = logging.StreamHandler()
        ssh.setLevel(conf.get("log", "sh_level"))
        autolog.addHandler(ssh)

        """
        时间格式
        """
        file = time.strftime("%Y-%m-%d")

        """
        创建输出到文件的日志等级
        """
        fh = logging.FileHandler(os.path.join(LOGDIR, f"{file}.log"))
        fh.setLevel(conf.get("log", "sh_level"))
        autolog.addHandler(fh)

        """
        定义输出日志的格式
        """
        formater = "%(asctime)s - [%(filename)s-->line:%(lineno)d] - %(levelname)s:%(message)s"
        fm = logging.Formatter(formater)
        ssh.setFormatter(fm)
        fh.setFormatter(fm)
        return autolog


log = HandleLog.create_log()

if __name__ == "__main__":
    log.debug(f"测试log:{time.strftime('%Y-%m-%d:%H:%M%S')}")
    log.error(f"测试log:{time.strftime('%Y-%m-%d:%H:%M%S')}")